import os
import numpy as np
import matplotlib.pyplot as plt


def problemB():
    # 读取文本文件
    data0 = np.loadtxt("txtfile/Bf0.txt")
    data1 = np.loadtxt("txtfile/Bf1.txt")
    data2 = np.loadtxt("txtfile/Bf2.txt")
    data3 = np.loadtxt("txtfile/Bf3.txt")
    data4 = np.loadtxt("txtfile/Bf4.txt")

    x = data0[:, 0]
    y0 = data0[:, 1]
    y1 = data1[:, 1]
    y2 = data2[:, 1]
    y3 = data3[:, 1]
    y4 = data4[:, 1]

    # 绘制两个函数的图像
    plt.figure(1, figsize=(10, 8))
    plt.plot(x, y0, label="Function exact")
    plt.plot(x, y1, label="Function n=2")
    plt.plot(x, y2, label="Function n=4")
    plt.plot(x, y3, label="Function n=6")
    plt.plot(x, y4, label="Function n=8")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("problem B")
    plt.legend()
    plt.grid(True)
    plt.savefig("pic/problemB.png")
    plt.show()


def problemC():
    # 读取文本文件
    data0 = np.loadtxt("txtfile/Cf0.txt")
    data1 = np.loadtxt("txtfile/Cf1.txt")
    data2 = np.loadtxt("txtfile/Cf2.txt")
    data3 = np.loadtxt("txtfile/Cf3.txt")
    data4 = np.loadtxt("txtfile/Cf4.txt")

    x = data0[:, 0]
    y0 = data0[:, 1]
    y1 = data1[:, 1]
    y2 = data2[:, 1]
    y3 = data3[:, 1]
    y4 = data4[:, 1]

    # 绘制两个函数的图像
    plt.figure(2, figsize=(10, 8))
    plt.plot(x, y0, label="Function exact")
    plt.plot(x, y1, label="Function n=5")
    plt.plot(x, y2, label="Function n=10")
    plt.plot(x, y3, label="Function n=15")
    plt.plot(x, y4, label="Function n=20")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("problem C")
    plt.legend()
    plt.grid(True)
    plt.savefig("pic/problemC.png")
    plt.show()


def problemD():
    data = np.loadtxt("txtfile/Df.txt")

    x = data[:, 0]
    y = data[:, 1]

    plt.figure(3, figsize=(10, 8))
    plt.plot(x, y, label="speed")
    plt.xlabel("time")
    plt.ylabel("velocity")
    plt.title("problem D")
    plt.legend()
    plt.grid(True)
    plt.savefig("pic/problemD.png")
    plt.show()


def problemE():
    # 读取文本文件
    data1 = np.loadtxt("txtfile/Ef1.txt")
    data2 = np.loadtxt("txtfile/Ef2.txt")

    x = data1[:, 0]
    y1 = data1[:, 1]
    y2 = data2[:, 1]

    # 绘制两个函数的图像
    plt.figure(4, figsize=(10, 8))
    plt.plot(x, y1, label="sp1")
    plt.plot(x, y2, label="sp2")
    plt.xlabel("day")
    plt.ylabel("weight")
    plt.title("problem E")
    plt.legend()
    plt.grid(True)
    plt.savefig("pic/problemE.png")
    plt.show()


# 创建一个文件夹
folder_name = "pic"  # 文件夹名称
if not os.path.exists(folder_name):
    os.makedirs(folder_name)

problemB()
problemC()
problemD()
problemE()
